package initialize

import (
	"bytes"
	"fmt"
	mqtt "github.com/mochi-mqtt/server/v2"
	"github.com/mochi-mqtt/server/v2/hooks/auth"
	"github.com/mochi-mqtt/server/v2/packets"
)

type IotMqttHook struct {
	auth.Hook
}

func (h *IotMqttHook) Provides(b byte) bool {
	return bytes.Contains([]byte{
		mqtt.OnConnectAuthenticate,
		mqtt.OnACLCheck,
		mqtt.OnStarted,
		mqtt.OnSubscribe,
		mqtt.OnPacketProcessed,
	}, []byte{b})
}

func (h *IotMqttHook) ID() string {
	return "iot-mqtt-hook"
}

func (h *IotMqttHook) OnStarted() {
	h.Log.Info("iot-mqtt-hook OnStart")
}

// OnSubscribe 订阅
func (h *IotMqttHook) OnSubscribe(cl *mqtt.Client, pk packets.Packet) packets.Packet {
	h.Log.Info(fmt.Sprintf("%s，订阅: %s", cl.ID, pk.TopicName))
	return pk
}

// OnPacketProcessed 接收到包
func (h *IotMqttHook) OnPacketProcessed(cl *mqtt.Client, pk packets.Packet, err error) {
	h.Log.Info(fmt.Sprintf("%s，OnPacketProcessed: %s", cl.ID, string(pk.Payload)))
}
